﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Xml;
using CarolLib.FTP;
using CarolLib.WinService;
using DispatchAssist.BusinessLogical.BLL;
using DispatchAssist.BusinessLogical.Configuration;
using DispatchAssist.BusinessLogical.DAL;
using DispatchAssist.BusinessLogical.Model;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System.IO;
using CarolLib;

namespace DispatchAssist.DMMsgGetter
{
    public class FlightBackUpGetter : IBasicTask
    {

        static FlightInfoManager manager;
        static ShareDicDownloadSetting Settings = ShareDicDownloadConfiguration.GetConfig().Settings;
        static log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public FlightBackUpGetter()
        {


        }

        public void Init()
        {
            manager = new FlightInfoManager();
        }



        public void Execute()
        {
            List<FileInfo> newFiles = null;
            try
            {
                //扫描共享目录并将新的文件扫描返回
                newFiles = DetectNewFiles();
            }
            catch (WebException webex)
            {
                Logger.Error("Error during ExecuteDetect", webex);
                return;
            }
            catch (Exception e)
            {
                Logger.Error("Error during ExecuteDetect", e);
                return;
            }

            if (newFiles.Count() == 0)
            {
                Logger.Info("No new files detected.");
                return;
            }
            else
            {
                Logger.InfoFormat("Start record {0} new files", newFiles.Count);
            }
            //解析航班备降场信息并更新数据到数据库
            ResolveNewFiles(newFiles);
        }

        public void Exit()
        {
            // throw new NotImplementedException();
        }

        #region 自定义方法
        private string GetMaxCreationTimeStr(List<FileInfo> sharedicList)
        {
            if (sharedicList == null || sharedicList.Count == 0) return "";
            DateTime dt = sharedicList[0].CreationTime;
            foreach (FileInfo finfo in sharedicList)
            {
                if (finfo.CreationTime.CompareTo(dt) > 0) dt = finfo.CreationTime;
            }
            return dt.ToString();
        }



        private List<FileInfo> GetRecentNewFiles(List<FileInfo> sharedicList)
        {
            List<FileInfo> resultList = new List<FileInfo>();


            string timestr = FileOperationHelper.read(Settings.FilePath);
            if (timestr == "")
            {
                resultList.AddRange(sharedicList);
            }
            else
            {
                DateTime lasttime = Convert.ToDateTime(timestr);
                foreach (FileInfo sharedicFile in sharedicList)
                {
                    if (sharedicFile.Extension.ToLower() == ".xml")
                    {
                        if (DateTime.Compare(DateTime.Parse(sharedicFile.CreationTime.ToString("yyyy-MM-dd HH:mm:ss")), lasttime) > 0)
                        {
                            resultList.Add(sharedicFile);
                        }
                    }
                }
            }
            if (resultList != null && resultList.Count != 0)
                FileOperationHelper.save(GetMaxCreationTimeStr(resultList), Settings.FilePath);

            return resultList;
        }
        /// <summary>
        /// serch new file
        /// </summary>
        /// <returns></returns>
        private List<FileInfo> DetectNewFiles()
        {

            List<FileInfo> resultList = new List<FileInfo>();
            //List<string> deleteList = new List<string>();
            //Dictionary<string, DateTime> recentList = manager.GetRecentFileNames(Settings.RecentDays);
            //if (recentList == null)
            //{
            //    return resultList;
            //}

            string localpath = Settings.ShareDicPath;

            DirectoryInfo dir = new DirectoryInfo(localpath);
            var sharedicList = dir.GetFiles("*.xml");
#if DEBUG
            Logger.InfoFormat("{0} files/dirs founded", sharedicList.Length);
#endif

            resultList = GetRecentNewFiles(sharedicList.ToList<FileInfo>());

            //foreach (FileInfo file in sharedicList)
            //{

            //    if (file.Extension.ToLower() == ".xml")
            //    {
            //        foreach (FileInfo sharedicFile in sharedicList)
            //        {
            //            if (((sharedicFile.LastWriteTime.Date >= DateTime.Today.AddDays(Settings.RecentDays * -1))))
            //            {
            //                //数据库中不存在的文件
            //                if (!recentList.Keys.Contains(sharedicFile.Name))
            //                {
            //                    resultList.Add(sharedicFile);
            //                }

            //            }
            //        }
            //    }
            //}


            return resultList;
        }

        private static DateTime getDateTimeByDateStr(string dateStr)
        {
            DateTime dt = new DateTime(1900, 1, 1);
            if (!string.IsNullOrEmpty(dateStr))
            {
                string ddS = dateStr.Substring(0, 2);
                string MMS = getMonth(dateStr.Substring(2, 3));
                string yyS = dateStr.Substring(5, 2);

                dt = Convert.ToDateTime("20" + yyS + "-" + MMS + "-" + ddS);

            }
            return dt;
        }


        private static DateTime ParseDateTimeStr(string dateStr)
        {
            System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US", true);

            if (dateStr.Length == 4)
            {
                return DateTime.ParseExact(dateStr, "dMMM", culture);

            }
            else if (dateStr.Length == 5)
            {
                return DateTime.ParseExact(dateStr, "ddMMM", culture);
            }
            else if (dateStr.Length == 7)
            {
                return DateTime.ParseExact(dateStr, "ddMMMyy", culture);
            }
            else if (dateStr.Length == 9)
            {
                return DateTime.ParseExact(dateStr, "ddMMMyyyy", culture);
            }
            else
            {
                throw new Exception("the Date Formate is Error");
            }
        }


        private static string getMonth(string mms)
        {
            string mm = "";
            switch (mms.ToUpper())
            {
                case "JAN":
                    mm = "01";
                    break;
                case "FEB":
                    mm = "02";
                    break;
                case "MAR":
                    mm = "03";
                    break;
                case "APR":
                    mm = "04";
                    break;
                case "MAY":
                    mm = "05";
                    break;

                case "JUN":
                    mm = "06";
                    break;
                case "JUL":
                    mm = "07";
                    break;
                case "AUG":
                    mm = "08";
                    break;
                case "SEP":
                    mm = "09";
                    break;
                case "OCT":
                    mm = "10";
                    break;

                case "NOV":
                    mm = "11";
                    break;
                case "DEC":
                    mm = "12";
                    break;
                default:
                    mm = "00";
                    break;
            }

            return mm;

        }

        private static void ResolveNewFiles(List<FileInfo> fileList)
        {
            foreach (var FileInfo in fileList)
            {
                XmlDocument xmlDoc = new XmlDocument();
                string filename = Settings.ShareDicPath + "\\" + FileInfo.Name; ;
                //xmlDoc.Load(@"E:\\Download\\REDZSWZ07020200.xml");
                try
                {
                    xmlDoc.Load(filename);
                    XmlNode xn_Carrier = xmlDoc.SelectSingleNode("/flight-plan-output/FPCFP/AirlineCode");

                    XmlNode xn_FlightNo = xmlDoc.SelectSingleNode("/flight-plan-output/FPCFP/FlightNumber");
                    XmlNode xn_PlanDeptTime = xmlDoc.SelectSingleNode("/flight-plan-output/FPCFP/LegDepartureDate");
                    XmlNode xn_DeptAirport = xmlDoc.SelectSingleNode("/flight-plan-output/FPCFP/Origin");


                    XmlNode xn_DeptBackup = xmlDoc.SelectSingleNode("/flight-plan-output/FPCFP/TakeOffAlternate");
                    XmlNode xn_ArrBackup = xmlDoc.SelectSingleNode("/flight-plan-output/FPCFP/Alternate");

                    XmlNode xn_SecondAlternate = xmlDoc.SelectSingleNode("/flight-plan-output/FPCFP/SecondAlternate");
                    XmlNode xn_RefileDestination = xmlDoc.SelectSingleNode("/flight-plan-output/FPCFP/RefileDestination");
                    XmlNode xn_RefileAlternate = xmlDoc.SelectSingleNode("/flight-plan-output/FPCFP/RefileAlternate");
                    //XmlNode xn_alarminfo = xmlDoc.SelectSingleNode("/flight-plan-output/FPCFP/alarminfo");
                    //XmlNode xn_Standard = xmlDoc.SelectSingleNode("/flight-plan-output/FPCFP/Standard");


                    string xn_CarrierStr = (xn_Carrier == null) ? "" : xn_Carrier.InnerText.Trim();

                    string xn_FlightNoStr = (xn_FlightNo == null) ? "" : xn_FlightNo.InnerText.Trim();
                    string xn_PlanDeptTimeStr = (xn_PlanDeptTime == null) ? "" : xn_PlanDeptTime.InnerText.Trim();

                    string xn_DeptAirportStr = (xn_DeptAirport == null) ? "" : xn_DeptAirport.InnerText.Trim();
                    if (xn_DeptAirportStr.Length > 3) xn_DeptAirportStr = InfoAirportHelper.GetApt3Code(xn_DeptAirportStr.Trim());
                    string xn_DeptBackupStr = (xn_DeptBackup == null) ? "" : xn_DeptBackup.InnerText.Trim();
                    if (xn_DeptBackupStr.Length > 3) xn_DeptBackupStr = InfoAirportHelper.GetApt3Code(xn_DeptBackupStr.Trim());

                    string xn_ArrBackupStr = (xn_ArrBackup == null) ? "" : xn_ArrBackup.InnerText.Trim();
                    if (xn_ArrBackupStr.Length > 3) xn_ArrBackupStr = InfoAirportHelper.GetApt3Code(xn_ArrBackupStr.Trim());

                    string xn_SecondAlternateStr = (xn_SecondAlternate == null) ? "" : xn_SecondAlternate.InnerText.Trim();
                    if (xn_SecondAlternateStr.Length > 3) xn_SecondAlternateStr = InfoAirportHelper.GetApt3Code(xn_SecondAlternateStr.Trim());

                    string xn_RefileDestinationStr = (xn_RefileDestination == null) ? "" : xn_RefileDestination.InnerText.Trim();
                    if (xn_RefileDestinationStr.Length > 3) xn_RefileDestinationStr = InfoAirportHelper.GetApt3Code(xn_RefileDestinationStr.Trim());


                    string xn_RefileAlternateStr = (xn_RefileAlternate == null) ? "" : xn_RefileAlternate.InnerText.Trim();
                    if (xn_RefileAlternateStr.Length > 3) xn_RefileAlternateStr = InfoAirportHelper.GetApt3Code(xn_RefileAlternateStr.Trim());

                    string RouteBackupStr = xn_SecondAlternateStr + "|" + xn_RefileDestinationStr + "|" + xn_RefileAlternateStr;

                    //System.IFormatProvider format = new System.Globalization.CultureInfo("zh-CN", true);
                    ////指定转换格式 
                    //string formatWarnTimrStr = DateTime.ParseExact(xn_PlanDeptTimeStr, "ddMMMyy", format).ToString("yyyy-MM-dd HH:mm:ss zzz"); ;

                    List<FlightInfo> flightInfoLst = manager.GetFlightInfoByPara(xn_CarrierStr, xn_FlightNoStr, ParseDateTimeStr(xn_PlanDeptTimeStr), xn_DeptAirportStr, 1);


                    if (flightInfoLst != null && flightInfoLst.Count > 0)
                    {
                        try
                        {
                            flightInfoLst[0].DeptBackup = xn_DeptBackupStr;
                            flightInfoLst[0].ArrBackup = xn_ArrBackupStr;
                            flightInfoLst[0].RouteBackup = RouteBackupStr;

                            int successCount = manager.DetectUpdateFlightBackUpInfo(flightInfoLst);
                            Logger.InfoFormat("{0} files have been recorded.", successCount);
                        }
                        catch (Exception e)
                        {

                            Logger.Warn("resolve failed." + e.Message, e);
                        }
                    }
                }
                catch (Exception e)
                {
                    Logger.Warn("resolve xml failed." + e.Message, e);
                }
            }
        }




        #endregion


    }
}
